//
//  FujinSekectView.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/3/1.
//  Copyright © 2016年 game. All rights reserved.
//

#import "FujinSekectView.h"
#import "CGFdbmBase.h"

#import "FujinCell.h"

#import "IslanDistance_typeModel.h"
#import "ValueModel.h"
#import "CityModel.h"

#define cellHeight (SCREEN_HEIGHT*0.063)

@interface FujinSekectView ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
/**
 *  承载tableview 跟选项btn的底部视图
 */
@property (nonatomic,strong) UIView *bacView;
@property (nonatomic,strong) UITableView *tableview;
/**
 *  地区数组
 */
@property (nonatomic,strong) NSMutableArray *Areas;
/**
 *  距离数组
 */
@property (nonatomic,strong) NSMutableArray *juliAry;
/**
 *  是否点击了区域
 */
@property (nonatomic,assign) BOOL isQuyu;
/**
 *  距离输入框
 */
@property (nonatomic,strong) UITextField *textField;
/**
 *  输入距离 点击确定btn
 */
@property (nonatomic,strong) UIButton *surBtn;

/**
 *  判断程序是否是第一次进来
 */
@property (nonatomic,assign) BOOL  isNoFirst;

@property (nonatomic,strong) IslanDistance_typeModel *distance;

@end

@implementation FujinSekectView

-(NSMutableArray *)juliAry{
    if (!_juliAry) {
        _juliAry = [NSMutableArray array];
    }
    return _juliAry;
}

-(NSMutableArray *)Areas{
    if (!_Areas) {
        _Areas = [NSMutableArray array];
    }
    return _Areas;
}

-(UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc]initWithFrame:CGRectMake(13, 6, screen_width/3, cellHeight+8-12)];
        _textField.font = font(SCREEN_WIDTH*0.035);
        _textField.borderStyle = 3;
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        _textField.leftView = [self textFileLweftView];
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.placeholder = @"请输入公里数";
    }
    return _textField;
}

-(UIView *)textFileLweftView{
    UIView *bacView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 25, cellHeight+8-12)];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn-search-grey"]];
    imageView.frame = CGRectMake(5,7,W(bacView)-7,W(bacView)-8);
    [bacView addSubview:imageView];
    return bacView;
}


-(UIButton *)surBtn{
    if (!_surBtn) {
        _surBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        _surBtn.frame= CGRectMake(Width(_textField)+15, Y(_textField)+3, W(_textField)*2/3, H(_textField)-6);
        [_surBtn setTitle:@"搜索" forState:UIControlStateNormal];
        [_surBtn setTitleColor:mainColor forState:UIControlStateNormal];
        _surBtn.layer.borderColor = mainColor.CGColor;
        _surBtn.layer.borderWidth = 0.6;
        _surBtn.titleLabel.font = font(SCREEN_WIDTH*0.045);
        [_surBtn addTarget:self action:@selector(CountSure) forControlEvents:UIControlEventTouchUpInside];
        radius(_surBtn, 4);

    }
    return _surBtn;
}

-(void)CountSure{

    if (_textField.text.length!=0) {
        if ([self.deleget respondsToSelector:@selector(FujinAlphaIsCellClick:AndIsQuyu:WhithSting:)]) {
            [self.deleget FujinAlphaIsCellClick:YES AndIsQuyu:NO WhithSting:_textField.text];
            _textField.text = @"";
            self.alpha = 0;
            self.isNoFirst = YES;
            [self.tableview reloadData];
        }
        
    }
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = TouMingBlack;
               UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selfTap)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
    }
    return self;
}

-(void)setDistanceModel:(NSArray *)distanceModel{

    _distanceModel = distanceModel;
    
    self.distance = _distanceModel[0];
    self.isQuyu = NO;
    self.isNoFirst = NO;
    [self CreatBacView];
    [self CreatTableview];
}

-(void)setLocalCity:(NSString *)localCity{
    _localCity = localCity;
    
    if ([self.localCity isEqualToString:@"巴音郭..."]) {
        self.localCity  = @"巴音郭楞蒙古";
    }
    
    /**
     *  先获取该城市的城市code
     */
    NSString *selectString= [NSString stringWithFormat:@"SELECT code FROM region_city WHERE short_name = '%@'",self.localCity];
    
    NSDictionary *dic = [CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_city" SelectSting:selectString].firstObject;
    
    NSString *cityCode = dic[@"code"];
    
     NSString *areSearch= [NSString stringWithFormat:@"SELECT * FROM region_area WHERE citycode = '%@'",cityCode];
    
      [self.Areas removeAllObjects];
    
    for (NSDictionary *dic in [CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_area" SelectSting:areSearch]) {
        
        [self.Areas addObject:[[CityModel alloc]initWithDictionary:dic error:nil]];
        
    }
    
    [self.Areas insertObject:[[CityModel alloc]initWithDictionary:@{@"name":@"全城",@"code":@""} error:nil] atIndex:0];
}

-(void)selfTap{
    
     [self.deleget FujinAlphaIsCellClick:NO AndIsQuyu:NO WhithSting:nil];
    self.alpha = 0;
}
/**
 *  点击backView 将键盘收起
 */
-(void)backViewTap{

    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
}
-(void)CreatBacView{

    
    [self.bacView removeFromSuperview];
    self.bacView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,cellHeight*(_distance.value.count+1)+8)];
    self.bacView.backgroundColor = linColor;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewTap)];
    tap.delegate = self;
    [self.bacView addGestureRecognizer:tap];
    
    [self addSubview:self.bacView];
    
    UIButton *juli =[UIButton buttonWithType:UIButtonTypeCustom];
    juli.backgroundColor = [UIColor whiteColor];
    juli.tag = 10;
    juli.frame = CGRectMake(0, 5, SCREEN_WIDTH/3, cellHeight);
    
    IslanDistance_typeModel *mode = self.distanceModel[0];
    
    [juli setTitle:mode.name forState:UIControlStateNormal];
    [juli addTarget:self action:@selector(Click:) forControlEvents:UIControlEventTouchUpInside];
    juli.adjustsImageWhenHighlighted=NO;
    [juli setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    juli.titleLabel.font = font(SCREEN_WIDTH*0.04);
    [self.bacView addSubview:juli];
    
    UIButton *quyu =[UIButton buttonWithType:UIButtonTypeCustom];
    quyu.tag = 11;
    quyu.backgroundColor = [UIColor clearColor];
    quyu.frame = CGRectMake(0, Height(juli), SCREEN_WIDTH/3, cellHeight);
    
    IslanDistance_typeModel *mode1 = self.distanceModel[1];
    [quyu setTitle:mode1.name forState:UIControlStateNormal];
    
    [quyu addTarget:self action:@selector(Click:) forControlEvents:UIControlEventTouchUpInside];
    
    [quyu setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    quyu.adjustsImageWhenHighlighted=NO;
   
    quyu.titleLabel.font = font(SCREEN_WIDTH*0.04);
    [self.bacView addSubview:quyu];
}

-(void)Click:(UIButton *)btn{
    [[[UIApplication sharedApplication]keyWindow] endEditing:YES];

        if (btn.tag==10) {
            self.bacView.height = cellHeight*(self.distance.value.count+1)+8;
            self.isQuyu = NO;
            self.tableview.scrollEnabled = NO;
            
        }else{
            
            self.bacView.height = cellHeight*4+70;
            self.isQuyu = YES;
            self.tableview.scrollEnabled = YES;
        }
         self.tableview.height = self.bacView.height;

    
    [self.tableview reloadData];
    
    for (int i=0; i<2; i++) {
        UIButton *bbb = [self viewWithTag:i+10];
        
        if (bbb.tag==btn.tag) {
            
            bbb.backgroundColor = [UIColor whiteColor];
            
        }else{
        
            bbb.backgroundColor = [UIColor clearColor];
        }
    }
}

-(void)CreatTableview{
    
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3, 0, SCREEN_WIDTH*2/3, H(self.bacView)) style:UITableViewStylePlain];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.tableview registerClass:[FujinCell class] forCellReuseIdentifier:@"cell"];
    
    self.tableview.scrollEnabled = NO;
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"quyuCell"];
    [self.bacView addSubview:self.tableview];
   
    self.tableview.tableFooterView = [UIView new];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isQuyu) {
        

        return self.Areas.count;
    }else{
        
        return  self.distance.value.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (self.isQuyu) {
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"quyuCell"];
        CityModel *model = self.Areas[indexPath.row];
        
        cell.textLabel.text = model.name;
        
        tableView.separatorStyle  = 1;
        cell.textLabel.font = font(SCREEN_WIDTH*0.04);
         return cell;
        
    }else{
        
        FujinCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        ValueModel *model = self.distance.value[indexPath.row];
        cell.text.text = model.name;
        tableView.separatorStyle  = 0;
        cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        
        if (!self.isNoFirst) {
            if (indexPath.row==0) {
                cell.lin.backgroundColor = mainColor;
                cell.text.textColor = mainColor;
            }
        }else{
            if (indexPath.row==0) {
                cell.lin.backgroundColor = [UIColor lightGrayColor];
                cell.text.textColor = [UIColor blackColor];
            }

        
        }


         return cell;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    if (self.isQuyu) {
        return 0;
    }else{
        return cellHeight+8;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    if (!self.isQuyu) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width*2/3,cellHeight+8 )];
        [view addSubview:self.textField];
        [view addSubview:self.surBtn];
        self.textField.alpha = 1;
        self.surBtn.alpha = 1;
        return view;
    }else{
        
        self.textField.alpha = 0;
        
        self.surBtn.alpha = 0;
    
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isQuyu) {
        
        CityModel *model = self.Areas[indexPath.row];
        [self.deleget FujinAlphaIsCellClick:YES AndIsQuyu:YES WhithSting:model.code];
        
    }else{
        FujinCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIView * allcellView = tableView.subviews[0];
        
        for (FujinCell * otherCell in allcellView.subviews) {
            
            if ([otherCell isKindOfClass:[FujinCell class]]) {
                otherCell.text.textColor = [UIColor blackColor];
                otherCell.lin.backgroundColor = [UIColor lightGrayColor];
            }
        }
        
        cell.lin.backgroundColor = mainColor;
        cell.text.textColor = mainColor;
        self.isNoFirst = YES;
        
        ValueModel *model = self.distance.value[indexPath.row];
        [self.deleget FujinAlphaIsCellClick:YES AndIsQuyu:NO WhithSting:model.range];
    }
   
    self.alpha = 0;
}

/**
 *  对某些手势进行 禁用
 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        
        return NO;
    }
    
    return YES;
}
@end
